﻿using EnumsNET;
using Kinlo.Entitys;
using Kinlo.MESDocking;
using LiveChartsCore;
using LiveChartsCore.Defaults;
using LiveChartsCore.Measure;
using LiveChartsCore.SkiaSharpView;
using LiveChartsCore.SkiaSharpView.Painting;
using NewLife.Data;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using UIWindows.Commands;
using UIWindows.GlobalStatics;
using UIWindows.Models;
using UIWindows.Models.Homes;
using UIWindows.Models.ParameterModels;
using UIWindows.Services;
using UIWindows.Tools.Helper;
using UIWindows.ViewModels.HomeItemViews;
using UIWindows.ViewModels.MesParameterItems;
using UIWindows.Views.DeviceInteractiveaddressItems;
using UIWindows.Views.HomeItemViews;
using UIWindows.Views.MesParameterItems;
using XingLucifer.IBase.Enums;
using static log4net.Appender.RollingFileAppender;
using static NPOI.HSSF.Util.HSSFColor;
using static System.Resources.ResXFileRef;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace UIWindows.ViewModels
{
    public class HomePageViewModel : UIWindows.Domains.ViewModelBase, XingLucifer.IBase.IViewStatus
    {
        #region 配置显示项
        public GridView ShortCircuitView { get; set; }
        public GridView BeforeWeightView { get; set; }
        public GridView ProductionDataView { get; set; }
        public GridView ShellInsertionDataView { get; set; }
        public GridView SpotoWeldDataView { get; set; }
        public GridView GrooveRollingMachineDataView { get; set; }
        public GridView ShortCircuitTesterDataView { get; set; }

        #endregion
        #region 注液统计
        public IEnumerable<ISeries> NG_MultiLiquidSeries { get; set; }
        public IEnumerable<ISeries> LiquidInjection_PassingRateSeries { get; set; }
        public IEnumerable<ISeries> NG_LessLiquidSeries { get; set; }
        #endregion

        #region 后称重
        public IEnumerable<ISeries> LiquidInjectionNGSeries { get; set; }
        public IEnumerable<ISeries> LeakDetectionNGSeries { get; set; }
        public IEnumerable<ISeries> AfterWeighingPassingRateSeries { get; set; }
        #endregion

        public GlobalStatics.ParameterStatic Parameter { get; set; }
        public GlobalStatics.HomeStatic Home { get; set; }
        public GlobalStatics.TemporaryStatic Temporary { get; set; }
        public DeviceInteractiveaddressStatic DeviceInteractiveaddressData { get; set; }
        public SystemConfigStatic _configStatic { get; set; }
        public DisplayItemsStatic _displayItems { get; set; }

        public FrontProcedure FrontProcedureView { get; set; }
        public CentralView centralView { get; set; }
        public AfertView afertView { get; set; }
        public TrayFillerView TrayFillerViews { get; set; }


        private bool _isShowFrontProcedure;


        /// <summary>
        /// 是否显示前段组装线
        /// </summary>
        public bool IsShowFrontProcedure
        {
            get { return _isShowFrontProcedure; }
            set
            {
                if (_isShowFrontProcedure != value)
                {
                    _isShowFrontProcedure = value;  // 更新属性的值
                    OnPropertyChanged(nameof(IsShowFrontProcedure));  // 通知属性已更改
                }
            }
        }

        public bool _isShowTrayFiller;
        /// <summary>
        /// 是否显示装盘页面
        /// </summary>
        public bool IsShowTrayFiller
        {
            get { return _isShowTrayFiller; }
            set
            {
                if (_isShowTrayFiller != value)
                {
                    _isShowTrayFiller = value;  // 更新属性的值
                    OnPropertyChanged(nameof(IsShowTrayFiller));  // 通知属性已更改
                }
            }
        }

        public bool _isCentral;
        /// <summary>
        /// 是否显示中段页面
        /// </summary>
        public bool IsCentral
        {
            get { return _isCentral; }
            set
            {
                if (_isCentral != value)
                {
                    _isCentral = value;  // 更新属性的值
                    OnPropertyChanged(nameof(IsCentral));  // 通知属性已更改
                }
            }
        }
        

        public bool _isShowAfert;
        /// <summary>
        /// 是否显示后段页面
        /// </summary>
        public bool IsShowAfert
        {
            get { return _isShowAfert; }
            set
            {
                if (_isShowAfert != value)
                {
                    _isShowAfert = value;  // 更新属性的值
                    OnPropertyChanged(nameof(IsShowAfert));  // 通知属性已更改
                }
            }
        }


        /// <summary>
        /// 是否显示前段
        /// </summary>
        //public bool IsShowFrontProcedure { get; set; }
        /// <summary>
        /// 是否显示装盘页面
        /// </summary>
        //public bool IsShowTrayFiller { get; set; }

        FrontProcedureViewModel frontProcedureViewModel { get; set; }
        CentralViewModel centralViewModel { get; set; }

        AfertViewModel afertViewModel { get; set; }

        TrayFillerViewViewModel trayFillerViewViewModel { get; set; }
        public HomePageViewModel(GlobalStatics.ParameterStatic parameter, GlobalStatics.HomeStatic home, GlobalStatics.TemporaryStatic temporaryStatic, SystemConfigStatic configStatic, DisplayItemsStatic displayItems, DeviceInteractiveaddressStatic deviceInteractiveaddressData)
        {

            DeviceInteractiveaddressData = deviceInteractiveaddressData;
            Parameter = parameter;
            Home = home;
            _configStatic = configStatic;
            _displayItems=displayItems;
            //ShortCircuitView = new GridView();
            //ProductionDataView = new GridView();
            //ShellInsertionDataView = new GridView();
            //SpotoWeldDataView = new GridView();
            //GrooveRollingMachineDataView = new GridView();
            //ShortCircuitTesterDataView = new GridView();


            BeforeWeightView = new GridView();

     

            //组装线前段页面
            frontProcedureViewModel = new FrontProcedureViewModel(parameter, home, temporaryStatic, configStatic, displayItems, deviceInteractiveaddressData);
            FrontProcedureView = new FrontProcedure
            {
                DataContext = frontProcedureViewModel
            };

            //组装线中段页面
            centralViewModel = new CentralViewModel(parameter, home, temporaryStatic, configStatic, displayItems, deviceInteractiveaddressData);
            centralView = new CentralView
            {
                DataContext = centralViewModel
            };

            //组装线后段页面
            afertViewModel = new AfertViewModel(parameter, home, temporaryStatic, configStatic, displayItems, deviceInteractiveaddressData);
            afertView = new AfertView
            {
                DataContext = afertViewModel
            };


            trayFillerViewViewModel = new TrayFillerViewViewModel(parameter, home, temporaryStatic, configStatic, displayItems, deviceInteractiveaddressData);
            //装盘页面
            TrayFillerViews = new TrayFillerView
            {
                DataContext = trayFillerViewViewModel
            };
            DeviceInteractiveaddressData = deviceInteractiveaddressData;
        }

        private bool IsShowView(MainDeviceTypeEnum typeEnum)
        {
            if (typeEnum == _configStatic.SCM.MainDeviceType)
            {
                return true;
            }
            return false;
        }

        public DelegateCommand ClockOutline => new DelegateCommand(() =>
        {

        });

        private List<DisplayItemsModel> _displayItems_ShortCircuit;
        private List<DisplayItemsModel> _displayItems_BeforeWeight;

        public void Load()
        {
            //if (_displayItems == null)
            //{
            //    _displayItems = Domains.ObjectContainer.ResolveSingleton<DisplayItemsStatic>();
            //}
            ////UpdateProductionDataViewColumns(ProductionDataView);
            //UpdateProductionDataViewColumns(ShellInsertionDataView, _displayItems.ShellInsertionDataDisplayItems);
            //UpdateProductionDataViewColumns(SpotoWeldDataView, _displayItems.SpotoWeldDataDisplayItems);
            //UpdateProductionDataViewColumns(GrooveRollingMachineDataView, _displayItems.GrooveRollingMachineDataDisplayItems);
            //UpdateProductionDataViewColumns(ShortCircuitTesterDataView, _displayItems.ShortCircuitTesterDataDisplayItems);
            //_displayItems.IsHomeUpdate = false;

           
            Application.Current.Dispatcher.Invoke(() =>
            {
                IsShowFrontProcedure = IsShowView(MainDeviceTypeEnum.前段组装线);
                if(IsShowFrontProcedure)
                {
                    frontProcedureViewModel.Load();
                }
                IsShowTrayFiller = IsShowView(MainDeviceTypeEnum.前段装盘机);
                if (IsShowTrayFiller)
                {
                    trayFillerViewViewModel.Load();  // 手动调用Load方法
                }
                IsCentral = IsShowView(MainDeviceTypeEnum.中段组装线);
                if (IsCentral)
                {
                    centralViewModel.Load();  // 手动调用Load方法
                }
                IsShowAfert = IsShowView(MainDeviceTypeEnum.后段组装线);
                if (IsShowAfert)
                {
                    afertViewModel.Load();  // 手动调用Load方法
                }
            });


            //UpdateProductionDataViewColumns(SpotoWeldDataView);
            //UpdateProductionDataViewColumns(GrooveRollingMachineDataView);
            //UpdateProductionDataViewColumns(ShortCircuitTesterDataView);
            //if (_displayItems == null)
            //{
            //    _displayItems = Domains.ObjectContainer.ResolveSingleton<DisplayItemsStatic>();
            //}
            //if (!_displayItems.IsHomeUpdate)
            //{
            //    return;
            //}
            //_displayItems.IsHomeUpdate = false;
            //ProductionDataView.Columns.Clear();
            ////ShellInsertionDataView.Columns.Clear();
            ////SpotoWeldDataView.Columns.Clear();
            ////GrooveRollingMachineDataView.Columns.Clear();
            ////ShortCircuitTesterDataView.Columns.Clear();

            //List<DisplayItemsModel> list = new List<DisplayItemsModel>(_displayItems.WeighingDisplayItems);
            //list.Sort((x, y) => x.CompareTo(y));
            //foreach (var item in list)
            //{
            //    if (item.IsDisplay)
            //    {
            //        GridViewColumn gvc = new GridViewColumn { Header = item.Description };
            //        if (item.DataType == "结果")
            //        {
            //            FrameworkElementFactory border = new FrameworkElementFactory(typeof(Border));
            //            border.SetValue(Border.CornerRadiusProperty, new CornerRadius(3));
            //            border.SetBinding(Border.BackgroundProperty, new Binding
            //            {
            //                Path = new System.Windows.PropertyPath(item.Name),
            //                Converter = new Tools.Converter.ResultToColorConverter()
            //            });

            //            FrameworkElementFactory text = new FrameworkElementFactory(typeof(TextBlock));
            //            text.SetValue(TextBlock.MarginProperty, new Thickness(5, 3, 5, 3));
            //            text.SetValue(TextBlock.ForegroundProperty, new SolidColorBrush(Colors.White));
            //            text.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Center);
            //            text.SetBinding(TextBlock.TextProperty, new Binding { Path = new System.Windows.PropertyPath(item.Name) });

            //            border.AppendChild(text);
            //            var dataTemplate = new DataTemplate();
            //            dataTemplate.VisualTree = border;
            //            gvc.CellTemplate = dataTemplate;
            //        }
            //        else if (item.DataType == "浮点型")
            //            gvc.DisplayMemberBinding = new Binding
            //            {
            //                Path = new System.Windows.PropertyPath(item.Name),
            //                StringFormat = "F2"
            //            };
            //        else if (item.DataType == "时间型")
            //            gvc.DisplayMemberBinding = new Binding
            //            {
            //                Path = new System.Windows.PropertyPath(item.Name),
            //                StringFormat = "yyyy-MM-dd HH:mm:ss",
            //                Converter = new Tools.Converter.TimeStampToDateTimeStringConverter()
            //            };
            //        else
            //            gvc.DisplayMemberBinding = new Binding { Path = new System.Windows.PropertyPath(item.Name) };
            //        ProductionDataView.Columns.Add(gvc);
            //        //ShellInsertionDataView.Columns.Add(gvc);
            //        //SpotoWeldDataView.Columns.Add(gvc);
            //        //GrooveRollingMachineDataView.Columns.Add(gvc);
            //        //ShortCircuitTesterDataView.Columns.Add(gvc);

            //    }
            //}
        }

        private void UpdateProductionDataViewColumns(GridView View, ObservableCollection<DisplayItemsModel> Items)
        {
           
            if (!_displayItems.IsHomeUpdate)
            {
                return;
            }
            
            View.Columns.Clear();

            List<DisplayItemsModel> list = new List<DisplayItemsModel>(Items);
            list.Sort((x, y) => x.CompareTo(y));

            foreach (var item in list)
            {
                if (item.IsDisplay)
                {
                    GridViewColumn gvc = new GridViewColumn { Header = item.Description };

                    if (item.DataType == "结果")
                    {
                        FrameworkElementFactory border = new FrameworkElementFactory(typeof(Border));
                        border.SetValue(Border.CornerRadiusProperty, new CornerRadius(3));
                        border.SetBinding(Border.BackgroundProperty, new Binding
                        {
                            Path = new System.Windows.PropertyPath(item.Name),
                            Converter = new Tools.Converter.ResultToColorConverter()
                        });

                        FrameworkElementFactory text = new FrameworkElementFactory(typeof(TextBlock));
                        text.SetValue(TextBlock.MarginProperty, new Thickness(5, 3, 5, 3));
                        text.SetValue(TextBlock.ForegroundProperty, new SolidColorBrush(Colors.White));
                        text.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Center);
                        text.SetBinding(TextBlock.TextProperty, new Binding { Path = new System.Windows.PropertyPath(item.Name) });

                        border.AppendChild(text);
                        var dataTemplate = new DataTemplate();
                        dataTemplate.VisualTree = border;
                        gvc.CellTemplate = dataTemplate;
                    }
                    else if (item.DataType == "浮点型")
                    {
                        gvc.DisplayMemberBinding = new Binding
                        {
                            Path = new System.Windows.PropertyPath(item.Name),
                            StringFormat = "F2"
                        };
                    }
                    else if (item.DataType == "时间型")
                    {
                        gvc.DisplayMemberBinding = new Binding
                        {
                            Path = new System.Windows.PropertyPath(item.Name),
                            StringFormat = "yyyy-MM-dd HH:mm:ss",
                            Converter = new Tools.Converter.TimeStampToDateTimeStringConverter()
                        };
                    }
                    else
                    {
                        gvc.DisplayMemberBinding = new Binding { Path = new System.Windows.PropertyPath(item.Name) };
                    }

                    View.Columns.Add(gvc);
                }
            }
        }


        public void UnLoad()
        {

        }
        void SetDisplayItemsShortCicute()
        {
            var temp = new MessageShortCircuitModel();
            _displayItems_ShortCircuit = new List<DisplayItemsModel>()
            {
                new DisplayItemsModel(){
                    Index = 1,
                    DataType = "结果",
                    Description = "总结果",
                    Name = nameof(temp.Result) ,//这个双向绑定的属性
                    SqlName = "ALL",//用来区分是什么设备
                },
                new DisplayItemsModel(){
                    Index = 2,
                    Description = "位 置",
                    Name = "Location",
                    SqlName = "ALL",
                },
                new DisplayItemsModel(){
                    Index = 3,
                    Description = "条 码",
                    Name = "BarCode",
                    SqlName = "ALL",
                },
                // new DisplayItemsModel(){
                //    Index = 4,
                //    DataType = "结果",
                //    Description = "开路结果",
                //    Name = nameof(temp.开路结果) ,//这个双向绑定的属性
                //    SqlName = DeviceTypes.RJ6902R_ShortCircuit.ToString(),
                //},
                //new DisplayItemsModel(){
                //  Index = 5,
                //  DataType = "结果",
                //  Description = "电阻测试结果",
                //  Name = nameof(temp.电阻测试结果) ,//这个双向绑定的属性
                //  SqlName = DeviceTypes.RJ6902R_ShortCircuit.ToString(),
                //},
                // new DisplayItemsModel(){
                //  Index = 6,
                //  DataType = "结果",
                //  Description = "电容测试结果",
                //  Name = nameof(temp.电容测试结果) ,//这个双向绑定的属性
                //  SqlName = DeviceTypes.RJ6902R_ShortCircuit.ToString(),
                //},
                //new DisplayItemsModel(){
                //    Index = 7,
                //    DataType = "结果",
                //    Description = "放电1结果",
                //    Name = nameof(temp.放电1结果) ,//这个双向绑定的属性
                //    SqlName = DeviceTypes.RJ6902R_ShortCircuit.ToString(),
                //},
                //new DisplayItemsModel(){
                //   Index = 8,
                //   DataType = "结果",
                //   Description = "放电2结果",
                //   Name = nameof(temp.放电2结果) ,//这个双向绑定的属性
                //   SqlName = DeviceTypes.RJ6902R_ShortCircuit.ToString(),
                //},
                //new DisplayItemsModel(){
                //   Index = 9,
                //   DataType = "结果",
                //   Description = "VP结果",
                //   Name = nameof(temp.VP结果) ,//这个双向绑定的属性
                //   SqlName = DeviceTypes.RJ6902R_ShortCircuit.ToString(),
                //},
                //new DisplayItemsModel(){
                //  Index = 10,
                //  DataType = "结果",
                //  Description = "跌落1结果",
                //  Name = nameof(temp.跌落1结果) ,//这个双向绑定的属性
                //  SqlName = DeviceTypes.RJ6902R_ShortCircuit.ToString(),
                //},
                //new DisplayItemsModel(){
                //  Index = 11,
                //  DataType = "结果",
                //  Description = "跌落2结果",
                //  Name = nameof(temp.跌落2结果) ,//这个双向绑定的属性
                //  SqlName = DeviceTypes.RJ6902R_ShortCircuit.ToString(),
                //},
                //new DisplayItemsModel(){
                //  Index = 12,
                //  DataType = "结果",
                //  Description = "跌落3结果",
                //  Name = nameof(temp.跌落3结果) ,//这个双向绑定的属性
                //  SqlName = DeviceTypes.RJ6902R_ShortCircuit.ToString(),
                //},
                //new DisplayItemsModel(){
                //  Index = 13,
                //  DataType = "结果",
                //  Description = "TL结果",
                //  Name = nameof(temp.TL结果) ,//这个双向绑定的属性
                //  SqlName = DeviceTypes.RJ6902R_ShortCircuit.ToString(),
                //},
                //new DisplayItemsModel(){
                //  Index = 14,
                //  DataType = "结果",
                //  Description = "TH结果",
                //  Name = nameof(temp.TH结果) ,//这个双向绑定的属性
                //  SqlName = DeviceTypes.RJ6902R_ShortCircuit.ToString(),
                //},
                //new DisplayItemsModel(){
                //    Index = 15,
                //    DataType = "浮点型",
                //    Description = "电阻值(MΩ)",
                //    Name =nameof(temp.ElectrodesTestValue),
                //    SqlName = "ALL",
                //},
                //new DisplayItemsModel(){
                //    Index = 16,
                //    Description = "电阻测试时间",
                //    Name =nameof(temp.ElectrodesTestTime),
                //    SqlName = "ALL",
                //},
                //new DisplayItemsModel(){
                //    Index = 17,
                //    DataType = "浮点型",
                //    Description = "电容测试数据",
                //    Name =nameof(temp.ElectrodesCapacitance),
                //    SqlName = DeviceTypes.RJ6902R_ShortCircuit.ToString(),
                //},
                //new DisplayItemsModel(){
                //    Index = 18,
                //    Description = "跌落1",
                //     Name =nameof(temp.跌落1),
                //    SqlName = DeviceTypes.RJ6902R_ShortCircuit.ToString(),
                //},
                //new DisplayItemsModel(){
                //    Index = 19,
                //    Description = "跌落2",
                //     Name =nameof(temp.跌落2),
                //    SqlName = DeviceTypes.RJ6902R_ShortCircuit.ToString(),
                //},
                // new DisplayItemsModel(){
                //    Index = 20,
                //    Description = "跌落3",
                //     Name =nameof(temp.跌落3),
                //    SqlName = DeviceTypes.RJ6902R_ShortCircuit.ToString(),
                //},
                //new DisplayItemsModel(){
                //    Index = 21,
                //    Description = "VP电压(v)",
                //    Name =nameof(temp.VP电压),
                //    SqlName = DeviceTypes.RJ6902R_ShortCircuit.ToString(),
                //},
                //new DisplayItemsModel(){
                //    Index = 22,
                //    Description = "升压时间(ms)",
                //    Name = "升压时间",
                //    SqlName = DeviceTypes.RJ6902R_ShortCircuit.ToString(),
                //},



            };

        }

        public DelegateCommand ClickMe => new DelegateCommand(() =>
        {
            MySqlHelper mySqlHelper = new MySqlHelper(Parameter.MESParameter.OthenDatabaseurl);
            var oneData = mySqlHelper.GetBatteryByCode("Empty83564123456789024720");
            if (oneData.status)
            {
                var NetWeight = oneData.netWeight;
                var OneAfterWeighing = oneData.outputWeight;
            }
        });
        void SetShowBeforWeight()
        {
            foreach (var item in _displayItems_BeforeWeight)
            {
                GridViewColumn gvc = new GridViewColumn { Header = item.Description };
                if (item.DataType == "结果")
                {
                    FrameworkElementFactory border = new FrameworkElementFactory(typeof(Border));
                    border.SetValue(Border.CornerRadiusProperty, new CornerRadius(3));
                    border.SetBinding(Border.BackgroundProperty, new Binding
                    {
                        Path = new System.Windows.PropertyPath(item.Name),
                        Converter = new Tools.Converter.ResultToColorConverter()
                    });

                    FrameworkElementFactory text = new FrameworkElementFactory(typeof(TextBlock));
                    text.SetValue(TextBlock.MarginProperty, new Thickness(5, 3, 5, 3));
                    text.SetValue(TextBlock.ForegroundProperty, new SolidColorBrush(Colors.White));
                    text.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Center);
                    text.SetBinding(TextBlock.TextProperty, new Binding { Path = new System.Windows.PropertyPath(item.Name) });

                    border.AppendChild(text);
                    var dataTemplate = new DataTemplate();
                    dataTemplate.VisualTree = border;
                    gvc.CellTemplate = dataTemplate;
                }
                else if (item.DataType == "浮点型")
                    gvc.DisplayMemberBinding = new Binding
                    {
                        Path = new System.Windows.PropertyPath(item.Name),
                        StringFormat = "F2"
                    };
                else if (item.DataType == "时间型")
                    gvc.DisplayMemberBinding = new Binding
                    {
                        Path = new System.Windows.PropertyPath(item.Name),
                        StringFormat = "yyyy-MM-dd HH:mm:ss",
                        Converter = new Tools.Converter.TimeStampToDateTimeStringConverter()
                    };
                else
                    gvc.DisplayMemberBinding = new Binding { Path = new System.Windows.PropertyPath(item.Name) };

                BeforeWeightView.Columns.Add(gvc);
            }


        }
        public DelegateCommand TestCMD => new DelegateCommand(() =>
        {
            int b = 239;
            double c = (double)b /240;
            double a = Math.Round(c, 4, MidpointRounding.ToNegativeInfinity) ;
            a = a * 100;
            $"{a}".MessageDialogs(MessageLevelType.信息, false, Enums.PopUpTypes.Global);
        });
    }

   
}
